<link rel="stylesheet" href="/content/js/jqgird/css/ui.jqgrid-bootstrap.css">
<link rel="stylesheet" href="/content/js/jqgird/plugins/bootstrap-datepicker.min.css">
<style>
    #entityRecordsModal table td{
        white-space:nowrap;
    }
</style>
<!-- （Modal） -->
<div class="modal fade in" id="entityRecordsModal" tabindex="-1" role="dialog"
     aria-labelledby="entityRecordsModalLabel" style="display:block;" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header" style="padding:5px;">
                <button type="button" class="close" data-dismiss="modal"
                        aria-hidden="true">
                    ×
                </button>
                <h4 class="modal-title" id="entityRecordsModalLabel">
                    <span class="glyphicon glyphicon-th"></span>
                </h4>
            </div>
            <div class="modal-body">
                <div id="queryview-section">
                    <div class="container-fluid">
                        <form id="searchForm" action="/api/entity/recordsdialog" onkeydown="if(event.keyCode==13)return false;" method="post" class="form-horizontal" data-jsonajax="true" data-formdata="false">
                            <input id="EntityId" name="entityid" data-name="entityid" type="hidden" />
                            <input id="SelectEntityRecordsQueryId" name="queryid" data-name="queryid" type="hidden" />
                            <input id="SortBy" name="sortby" data-name="sortby" type="hidden" value="createdon" />
                            <input data-val="true" id="SortDirection" name="sortdirection" data-name="sortdirection" type="hidden" />
                            <input type="hidden" name="page" data-name="page" value="1" />
                            <input type="hidden" name="qfield" data-name="qfield" id="QField" value="name" />
                            <input type="hidden" name="mutilChecker" id="mutilChecker" value="" />
                            <div class="form-group" style="margin-bottom:5px;">
                                <div class="col-sm-2">
                                    <label>名称</label>
                                    <!--<a id="fieldDropdown" class="dropdown-toggle btn btn-link btn-sm" data-toggle="dropdown" href="#">
                                        <span>搜索字段</span> <span class="caret"></span>
                                    </a>
                                    <ul class="dropdown-menu">
                                        &lt;!&ndash;<li><a href="javascript:void(0)" data-name="">全部字段</a></li>&ndash;&gt;
                                        <li><a href="javascript:void(0)" data-name="name" data-type="nvarchar">名称</a></li>
                                    </ul>-->
                                </div>
                                <div class=" col-sm-4" style="width:282px;">
                                    <div class="input-group input-group-sm">
                                        <input class="form-control" id="Q" name="Q" placeholder="快速查询" style="width:200px;" type="text" value="" />
                                        <span class="input-group-btn">
                                            <button class="btn btn-default" type="button" name="clearBtn">
                                                <span class="glyphicon glyphicon-remove-sign"></span>
                                            </button>
                                            <button class="btn btn-default" type="button" name="searchBtn">
                                                <span class="glyphicon glyphicon-search"></span>
                                            </button>
                                        </span>
                                    </div>
                                </div>
                                <div class="input-group input-group-sm col-sm-3" id="filterSearcher">
                                </div>
                            </div>
                        </form>
                    </div>
                    <div class="panel panel-default " id="gridview" style="margin-bottom:0;">
                        <div class="table-responsive" style="min-height:300px;max-height:350px;">
                            <table class="table table-hover table-striped table-condensed datatable" data-pageurl="/xms/api/entity/recordsdialog" data-ajax="true" data-ajaxcontainer="gridview" data-ajaxcallback="EntityRecordsModel.ajaxgrid_reset()" data-sortby="createdon" data-sortdirection="1" data-singlemode="true" style="table-layout:fixed;">
                                <thead>
                                <tr>
                                    <th width="22"><input type="checkbox" name="checkall" /></th>
                                    <th width="35"></th>
                                </tr>
                                </thead>
                                <tbody>
                                </tbody>
                            </table>
                        </div>
                        <div class="panel-footer" style="padding:3px 5px;">
                            <div class="row">
                                <div id="page-text" class="col-sm-4">
                                </div>
                                <div id="page-selection" class="col-sm-8 page-selection" data-total="1" data-page="1"></div>
                            </div>
                        </div>
                    </div>
                    <div class="selectEntityRecords-datagrid"></div>
                </div>
                <script src="/content/js/jquery.bootpag.min.js"></script>
                <script src="/content/js/jquery.form.js"></script>
                <script src="/content/js/bootstrap-datepicker-1.5.0/js/bootstrap-datepicker.min.js"></script>
                <script src="/content/js/bootstrap-datepicker-1.5.0/locales/bootstrap-datepicker.zh-CN.min.js" charset="UTF-8"></script>
                <script src="/content/js/fetch.js"></script>
                <script src="/content/js/xms.utility.js"></script>
                <script>
                ;(function () {
                    var MODAL_GUID = Xms.Utility.Guid.NewGuid().ToString('N');
                    var paramsModel = $.urlParamObj(decodeURIComponent($('#entityRecordsModal').parent().attr('data-dialog')));
                    paramsModel.callback = decodeURIComponent($('#entityRecordsModal').parent().attr('data-callback'));
                    var EntityRecordsModel = {
                        dialogid: '#entityRecordsModal',
                        dialog: $('#entityRecordsModal'),
                        datatable: $('#entityRecordsModal .datatable'),
                        pageUrl: decodeURIComponent($('#entityRecordsModal').parent().attr('data-dialog')),
                        queryid: paramsModel.queryid || '',
                        entityid: paramsModel.entityid || '',
                        entityname: paramsModel.entityname || '',
                        cacheFilters:new Xms.Fetch.FilterExpression(),
                        filters: paramsModel.filter || {},
                        sortby: 'createdon',
                        sortdir: '1',
                        q: '',
                        qfield: '',
                        page: 1,
                        pagesize: 10,
                        //currentUrl:'',
                        callback:(paramsModel.callback && getFunction(paramsModel.callback)) || null,
                        inputid: paramsModel.inputid,
                        singlemode: paramsModel.singlemode || true,
                        checkedList:[],
                        getData: function(m){
                            Xms.Web.Post('/api/entity/recordsdialog', m, false, function(res){
                                console.log('getData', res);
                                if(!res.IsSuccess){
                                    Xms.Web.FailureHandler(res, function(){
                                        EntityRecordsModel.dialog.find('.close').trigger('click');
                                    });
                                    return;
                                }
                                res = res.Content;
                                EntityRecordsModel.queryid = res.QueryView.queryviewid;
                                EntityRecordsModel.entityid = res.QueryView.entityid;
                                EntityRecordsModel.entityname = res.QueryView.entityname;
                                $('#entityRecordsModalLabel').html('<span class="glyphicon glyphicon-th"></span> '+res.EntityList[0].localizedname + ' - ' + res.QueryView.name);
                                $('#page-text').text('当前'+res.page+'/'+res.totalpages+'页, 共'+res.totalitems+'行记录');
                                $('#page-selection').attr({'data-total': res.totalpages, 'data-page': res.page});
                                var primaryKey = $.grep(res.AttributeList, function(nn, ii){
                                    return nn.entityid == EntityRecordsModel.entityid && nn.attributetypename == 'primarykey';
                                })[0];
                                var primaryField = $.grep(res.AttributeList, function(nn, ii){
                                    return nn.entityid == EntityRecordsModel.entityid && nn.isprimaryfield == true;
                                })[0];
                                var _head = EntityRecordsModel.datatable.find('thead>tr');
                                _head.find('[data-name]').remove();
                                $(res.Grid.Rows[0].Cells).each(function(i, cell){
                                    var isrelated = cell.Name.indexOf(".") > 0;
                                    var k = isrelated ? cell.Name.split('.')[1] : cell.Name.toLowerCase();
                                    var label = cell.Label;
                                    var itemStr = "";
                                    var attr = null;
                                    if (!isrelated)
                                    {
                                        var attrs = $.grep(res.AttributeList, function(nn, ii){
                                            return nn.entityid == EntityRecordsModel.entityid && nn.name == k;
                                        });
                                        attr = (attrs && attrs.length > 0 ? attrs[0] : null);
                                    }
                                    else
                                    {
                                        var attrs = $.grep(res.AttributeList, function(nn, ii){
                                            return nn.entityname == cell.EntityName && nn.name == k;
                                        });
                                        attr = (attrs && attrs.length > 0 ? attrs[0] : null);
                                    }
                                    if (attr == null) { return true; }
                                    if (attr.attributetypename == 'picklist' || attr.attributetypename == 'status')
                                    {
                                        if(attr.optionset && attr.optionset.items) {
                                            itemStr = encodeURIComponent(JSON.stringify(attr.optionset.items));
                                        }
                                    }
                                    else if(attr.attributetypename == 'bit' || attr.attributetypename == 'state'){
                                        if(attr.picklists) {
                                            itemStr = encodeURIComponent(JSON.stringify(attr.picklists));
                                        }
                                    }
                                    var _th = $('<th></th>');
                                    _th.prop('style', 'width:' + cell.Width + 'px');
                                    _th.attr('data-name', cell.Name);
                                    _th.attr('data-label', cell.Label);
                                    _th.attr('data-entityid', attr.entityid);
                                    _th.attr('data-referencedentityid', attr.referencedentityid);
                                    _th.attr('data-opts', itemStr);
                                    _th.attr('data-type', attr.attributetypename);
                                    //_th.text(label);
                                    _head.append(_th);
                                });
                                var _body = EntityRecordsModel.datatable.find('tbody');
                                _body.empty();
                                $(res.items).each(function(i, item){
                                    var recordid = item[primaryKey.name];
                                    var _row = $('<tr></tr>');
                                    //_row.attr('data-dbclick', "");
                                    _row.attr('data-id', recordid);
                                    _row.append('<td><input type="checkbox" name="recordid" value="'+recordid+'" /></td>');
                                    _row.append('<td><input type="hidden" name="recordname" value="'+item[primaryField.name]+'" /><a class="btn btn-link btn-xs selectBtn"><span class="glyphicon glyphicon-ok"></span></a></td>');
                                    //_row.on('dbclick', function(){EntityRecordsModel.selectedrow(recordid);});
                                    $(res.Grid.Rows[0].Cells).each(function(i, cell) {
                                        var isrelated = cell.Name.indexOf(".") > 0;
                                        var k = isrelated ? cell.Name.split('.')[1] : cell.Name.toLowerCase();
                                        var attr = null;
                                        if (!isrelated) {
                                            attr = $.grep(res.AttributeList, function (nn, ii) {
                                                return nn.entityid == EntityRecordsModel.entityid && nn.name == k;
                                            });
                                        } else {
                                            attr = $.grep(res.AttributeList, function (nn, ii) {
                                                return nn.entityname == cell.EntityName && nn.name == k;
                                            });
                                        }
                                        if (attr == null) {
                                            return true;
                                        }
                                        attr = attr[0];
                                        var columnName = cell.Name.toLowerCase();
                                        var value = item[columnName];
                                        var _td = $('<td></td>');
                                        if (attr.attributetypename == 'primarykey' || attr.attributetypename == 'lookup' || attr.attributetypename == 'owner')
                                        {
                                            columnName = attr.attributetypename == 'primarykey' ? primaryField.name : columnName += "name";
                                            value = item[columnName] || '';
                                            recordid = item[cell.Name.toLowerCase()];
                                            /*if(attr.attributetypename == 'primarykey' || attr.displaystyle == 'link'){
                                                _td.append('<a href="'+ORG_SERVERURL+'/entity/edit?entityid='+attr.referencedentityid+'&recordid='+recordid+'" target="_blank" title="">'+value+'</a>');
                                            }
                                            else{*/
                                                _td.text(value);
                                            //}
                                        }
                                        else if (attr.attributetypename == 'picklist' || attr.attributetypename == 'status' || attr.attributetypename == 'bit' || attr.attributetypename == 'state'){
                                            columnName += "name";
                                            _td.text(item[columnName] || '');
                                        }
                                        else if (attr.isprimaryfield)
                                        {
                                            _td.text(value || '');
                                            //_td.append('<a href="'+ORG_SERVERURL+'/entity/create?entityid='+attr.entityid+'&recordid='+recordid+'" target="_blank">'+(value || '')+'</a>');
                                        }
                                        else
                                        {
                                            if (value != null && (attr.attributetypename == 'decimal'
                                                                    || attr.attributetypename == 'float'))
                                            {
                                                value = value.toFixed(2);
                                            }
                                            else if (value != null && attr.attributetypename == 'money')
                                            {
                                                value = "￥" + value.toFixed(2);
                                            }
                                            else if (value != null && attr.attributetypename == 'datetime')
                                            {
                                                if (attr.DataFormat == "yyyy/MM/dd")
                                                {
                                                    value = (new Date(value)).Format("yyyy/MM/dd");
                                                }
                                                //value = string.Format("{0:G}", value);
                                            }
                                            _td.text(value || '');
                                        }
                                        _td.prop('title', _td.text());
                                        _row.append(_td);
                                    });
                                    _body.append(_row);
                                });
                                EntityRecordsModel.ajaxgrid_reset();
                            }, null, false, false);
                        },
                        ajaxTable : function () {
                            var self = $('#entityRecordsModal .datatable');
                            var containerId = '#' + self.attr('data-ajaxcontainer');
                            $(EntityRecordsModel.dialogid + " " + containerId).find('a[data-ajax="true"]').off('click');
                            $(EntityRecordsModel.dialogid + " " + containerId).parent().delegate('a[data-ajax="true"]', 'click', function () {
                                var url = $(this).attr('href');
                                url = url + (url.indexOf('?') == -1 ? '?' : '&') + '__r=' + new Date().getTime();
                                var model = $.urlParamObj(url);
                                //EntityRecordsModel.pageUrl = url;
                                //$("#entityRecordsModal .datatable").attr('data-pageurl',url);
                                EntityRecordsModel.sortby = model.sortby;
                                EntityRecordsModel.sortdir = model.sortdirection;
                                EntityRecordsModel.page=1;
                                EntityRecordsModel.rebind();
                                return false;
                            });
                        },
                        ajaxgrid_reset : function () {
                            EntityRecordsModel.datatable.attr('data-singlemode', EntityRecordsModel.singlemode);
                            EntityRecordsModel.datatable.attr('data-sortby', EntityRecordsModel.sortby);
                            EntityRecordsModel.datatable.attr('data-sortdirection', EntityRecordsModel.sortdir);
                            EntityRecordsModel.pageUrl = EntityRecordsModel.datatable.attr('data-pageurl');
                            EntityRecordsModel.pag_init();
                            var $inputid = $('#'+EntityRecordsModel.inputid);
                            var $mutilChecker = $('#mutilChecker')
                            if(!EntityRecordsModel.singlemode && $inputid.length>0 && $inputid.val()!=='' && $inputid.attr('data-value') && $inputid.attr('data-value')!=""){
                                try{
                                    var checklist = $inputid.attr('data-value').split(',');
                                    var checknamelist = $inputid.val().split(',');
                                    var _res = [];
                                    $.each(checklist,function(key,item){
                                        var tempobj = {
                                            id:item,
                                            name:checknamelist[key]
                                        }
                                        _res.push(tempobj);
                                    });
                                    $mutilChecker.val(encodeURIComponent(JSON.stringify(_res)));
                                }catch(e){
                                    console.log(e);
                                }
                            }

                            EntityRecordsModel.datatable.removeAttr('data-datatableinit');
                            Xms.Web.DataTable(EntityRecordsModel.datatable,{
                                changeHandler:function(obj,type,target){
                                    if(type=='item'){
                                        var $obj = null
                                        if($(obj).find('input[name="recordid"]').length==0){
                                            $obj = $(obj);
                                        }else{
                                            $obj = $(obj).find('input[name="recordid"]');
                                        }
                                        var _check = $obj.prop('checked');
                                        if(_check){
                                            EntityRecordsModel._addRowInHidden();
                                        }else{
                                            EntityRecordsModel._removeRowByHidden($obj.val());
                                        }
                                    }else{

                                        var _check = $(obj).prop('checked');
                                        if(_check){
                                            EntityRecordsModel._addRowInHidden();
                                        }else{
                                            EntityRecordsModel.datatable.find('tbody').find('input[name="recordid"]').each(function(){

                                                EntityRecordsModel._removeRowByHidden($(this).val());

                                            });
                                        }

                                    }
                                    console.log('changeHandler',_check)
                                },
                                dbClick: function(e){
                                    $(e).find('.selectBtn').trigger('click');
                                }
                            });
                            console.log('pageclick');
                            if(EntityRecordsModel.singlemode==false){

                                console.log('tr.click.binding');
                                EntityRecordsModel.dialog.find(".datatable tbody tr").off('tr.click').on('tr.click',function(e,data){
                                    var $self = $(this);
                                    var id = $(this).find('input[name=recordid]').val();
                                    console.log('tr.click.trigger',data);
                                    if(data.flag){
                                        if(id){
                                            //console.log('tr.click._removeRowByHidden',id);
                                            // EntityRecordsModel._removeRowByHidden(id);
                                            console.log('remove');
                                        }
                                    }else{
                                        console.log('add');
                                        //  EntityRecordsModel._addRowInHidden();
                                    }
                                });
                                EntityRecordsModel._changepageChecked();
                            }
                            //EntityRecordsModel.ajaxTable();
                            //EntityRecordsModel.datatable.find('tbody>tr').each(function(i, n){
                            //    $(n).bind('dbclick', function(e){alert('abc');
                            //        Xms.Web.SelectingRow(this);
                            //        EntityRecordsModel.dialog_return();
                            //    });
                            //});
                            EntityRecordsModel._changepageChecked();
                        },
                        _changepageChecked:function(){
                            var $mutilChecker = $('#mutilChecker'),checkedData = $mutilChecker.val();
                            if(checkedData!=''){
                                checkedData = JSON.parse(decodeURIComponent(checkedData));
                            }
                            console.log('checkedData',checkedData);
                            if(checkedData && checkedData.length>0){
                                EntityRecordsModel.dialog.find(".datatable").find("input[name=recordid]").each(function (i, n) {
                                    var flag = false;
                                    $.each(checkedData,function(ii,nn){
                                        if(nn.id == $(n).val()){//如果有重复的就不加进去
                                            flag = true;
                                        }
                                    });
                                    if(flag==true){
                                        $(this).prop('checked',true);
                                    }
                                });
                            }
                        },
                        _removeRowByHidden:function(id){
                            var $mutilChecker = $('#mutilChecker'),checkedData = $mutilChecker.val();
                            var checkedData1= null;
                            if($mutilChecker.val()!=''){
                                checkedData1 = JSON.parse(decodeURIComponent($mutilChecker.val()));
                            }

                            if(checkedData1){
                                var delIndex = null;
                                $.each(checkedData1,function(ii,nn){
                                    if(nn.id == id){//如果有重复的就不加进去
                                        delIndex = ii;
                                        return false;
                                    }
                                });
                                if(~delIndex){
                                    checkedData1.splice(delIndex,1);
                                    console.log('checkedData1',checkedData1);
                                    if(checkedData1.length==0){
                                        $mutilChecker.val('');
                                    }else{
                                        $mutilChecker.val(encodeURIComponent(JSON.stringify(checkedData1)));
                                    }
                                }
                            }
                        },
                        _addRowInHidden:function(){
                            var $mutilChecker = $('#mutilChecker'),checkedData = $mutilChecker.val();

                            if(checkedData!=''){
                                checkedData = JSON.parse(decodeURIComponent(checkedData));
                            }

                            if(checkedData && checkedData.length>0){
                                //防止添加重复的数据
                                var result = [];
                                EntityRecordsModel.dialog.find(".datatable").find("input[name=recordid]:checked").each(function (i, n) {
                                    var flag = false;
                                    $.each(checkedData,function(ii,nn){
                                        if(nn.id == $(n).val()){//如果有重复的就不加进去
                                            flag = true;
                                        }
                                    });
                                    if(flag==false){
                                        var obj = new Object();
                                        obj.id = $(n).val();
                                        obj.name = $(n).parents('tr:first').find('input[name=recordname]').val();
                                        result.push(obj);
                                    }
                                });
                                checkedData = checkedData.concat(result);
                            }else{
                                var result = [];
                                EntityRecordsModel.dialog.find(".datatable").find("input[name=recordid]:checked").each(function (i, n) {
                                    var obj = new Object();
                                    obj.id = $(n).val();
                                    obj.name = $(n).parents('tr:first').find('input[name=recordname]').val();
                                    result.push(obj);
                                });
                                checkedData = result;
                            }
                            console.log('checkedData',checkedData)
                            $mutilChecker.val(encodeURIComponent(JSON.stringify(checkedData)));
                        },
                        _emptyCheckerValue:function(){
                            var $mutilChecker = $('#mutilChecker'),checkedData = $mutilChecker.val();
                            $mutilChecker.val('');
                        },
                        pag_init : function () {
                            var a = $(EntityRecordsModel.dialogid + ' .page-selection');
                            var pageSetting = {
                                total: a.attr('data-total')
                                , maxVisible: 5
                                , page: a.attr('data-page')
                                , leaps: false
                                , prev: '&lsaquo;'
                                , next: '&rsaquo;'
                                , firstLastUse: true
                                , first: '&laquo;'
                                , last: '&raquo;'
                            };
                            $(EntityRecordsModel.dialogid + ' .page-selection').bootpag(pageSetting).off("page");
                            $(EntityRecordsModel.dialogid + ' .page-selection').bootpag(pageSetting).on("page", function (event, /* page number here */ num) {
                                event.preventDefault();
                                EntityRecordsModel.page = num;
                                EntityRecordsModel.rebind();
                                return false;
                            });
                        },
                        rebind: function (url,filters) {
                            var url = url || '/api/entity/recordsdialog';
                            url = url + (url.indexOf('?') == -1 ? '?' : '&') + '__r=' + new Date().getTime();
                            var model = new Object();
                            model.EntityId = EntityRecordsModel.entityid;
                            model.EntityName = EntityRecordsModel.entityname;
                            model.QueryId = EntityRecordsModel.queryid;
                            if(EntityRecordsModel.cacheFilters && EntityRecordsModel.cacheFilters.Filters && EntityRecordsModel.cacheFilters.Filters.length>0){
                                var __filter =  new Xms.Fetch.FilterExpression();
                                __filter.Filters.push(EntityRecordsModel.filters);
                                var filters = EntityRecordsModel.cacheFilters;
                                $.each(filters.Filters,function(key,filter){
                                    if (filter.Conditions[0]
                                        && typeof filter.Conditions[0].Values === "object" && filter.Conditions[0].Values.length
                                        && filter.Conditions[0].Values[0].replace("\s", "") != ""
                                        || (filter.Conditions[0] && filter.Conditions[0].Values && filter.Conditions[0].Values.length>0 && filter.Conditions[0].Values[1] && filter.Conditions[0].Values[1].replace("\s", "") != "")
                                    ) {
                                        __filter.Filters.push(this);
                                    }

                                });
                                model.Filter = __filter;
                            }else{
                                model.Filter = filters || EntityRecordsModel.filters;
                            }
                            model.Q = EntityRecordsModel.q;
                            model.QField = EntityRecordsModel.qfield;
                            model.SortBy = EntityRecordsModel.sortby;
                            model.SortDirection = EntityRecordsModel.sortdir;
                            //model.InputId = EntityRecordsModel.inputid;
                            //model.CallBack = EntityRecordsModel.callback;
                            model.Page = EntityRecordsModel.page;
                            model.pagesize = EntityRecordsModel.pagesize;
                            model.SingleMode = EntityRecordsModel.singlemode;
                            model.OnlyEnabledRecords = false;
                            console.log('rebind.model',model);
                            EntityRecordsModel.getData(model);
                        },
                        getNum_String: function(s){
                            return s.replace(/[^0-9]/ig,"")
                        },
                        selectedrow: function(id){
                            EntityRecordsModel.dialog.find('tr[data-id="'+id+'"]').find('.selectBtn').trigger('click');
                        },
                        dialog_return : function (obj) {
                            var result = new Array();
                            if(!obj){
                                EntityRecordsModel.dialog.find(".datatable").find("input[name=recordid]:checked").each(function (i, n) {
                                    var obj = new Object();
                                    obj.id = $(n).val();
                                    obj.name = $(n).parents('tr:first').find('input[name=recordname]').val();
                                    result.push(obj);
                                });
                            }else{//防止多选时，始终是传回第一个已勾选上的值
                                var partr = $(obj).parents('tr:first');
                                var partrDom = partr.get(0);
                                var partrobj = {
                                    id:partr.find("input[name=recordid]").val(),
                                    name:partr.find('input[name=recordname]').val()
                                }
                                result.push(partrobj);
                                EntityRecordsModel.dialog.find(".datatable").find("input[name=recordid]:checked").each(function (i, n) {
                                    if($(n).parents('tr:first').get(0)==partrDom){return true;}
                                    var obj = new Object();
                                    obj.id = $(n).val();
                                    obj.name = $(n).parents('tr:first').find('input[name=recordname]').val();
                                    result.push(obj);
                                });
                            }

                            if(EntityRecordsModel.singlemode==false){
                                var $mutilChecker = $('#mutilChecker'),checkedData = $mutilChecker.val();
                                if(checkedData!=''){
                                    checkedData = JSON.parse(decodeURIComponent(checkedData));
                                    result = checkedData;
                                }
                            }
                            if(result.length == 0){
                                Xms.Web.Alert(false, LOC_NOTSPECIFIED_RECORD);
                                return;
                            }
                            var dialog = $(EntityRecordsModel.dialogid);
                            console.log(result, EntityRecordsModel.inputid, dialog.data().OpenDialogCallback);
                            if (dialog.data().OpenDialogCallback) {
                                dialog.data().OpenDialogCallback(result, EntityRecordsModel.inputid)
                            } else if(EntityRecordsModel.callback) {
                                EntityRecordsModel.callback && EntityRecordsModel.callback(result, EntityRecordsModel.inputid);
                            } else{
                                $('#' + EntityRecordsModel.inputid.val(JSON.stringify(result)));
                            }

                            if($("#"+EntityRecordsModel.inputid).length>0){
                                $("#"+EntityRecordsModel.inputid).trigger("dialog.return",result);
                            }
                            //Xms.Web.Event.publish({result:result, inputid: EntityRecordsModel.inputid});
                            EntityRecordsModel.dialog.modal('hide');
                            //Xms.Web.CloseDialog('#entityRecordsModal');
                        },
                        CreateRecord: function () {
                            var url = '/entity/create?entityid=' + EntityRecordsModel.entityid;
                            Xms.Web.OpenWindow(ORG_SERVERURL+url);
                        }
                        ,enterSearch :function(e){
                            console.log(e);
                            e = e || window.event;
                            if(e.preventDefault){
                                e.preventDefault();
                            }else{
                                e.returnValue = false;
                            }
                            EntityRecordsModel.page = 1;
                            EntityRecordsModel.q = $(EntityRecordsModel.dialogid + ' #Q').val();
                            EntityRecordsModel.qfield = $(EntityRecordsModel.dialogid + ' #QField').val();
                            EntityRecordsModel.rebind();
                        }
                    };
                    $(function () {
                        // EntityRecordsModel.rebind(EntityRecordsModel.pageUrl);
                        //默认第一列为快速查找字段
                        //$(EntityRecordsModel.dialogid+' #fieldDropdown').next().find('a:eq(1)').trigger('click');
                        EntityRecordsModel.dialog.modal({
                            backdrop:'static'
                        });
                        EntityRecordsModel.dialog.on('hidden.bs.modal', function () {
                            Xms.Web.CloseDialog(EntityRecordsModel.dialogid);
                        });
                        EntityRecordsModel.rebind();
                        EntityRecordsModel.ajaxTable();
                        $(EntityRecordsModel.dialogid + ' button[name=clearBtn]').off('click').on('click',null,function(e){
                            $(EntityRecordsModel.dialogid + ' #Q').val('');
                            EntityRecordsModel.q = '';
                            EntityRecordsModel.cacheFilters = new Xms.Fetch.FilterExpression();
                            EntityRecordsModel.rebind();
                            EntityRecordsModel._emptyCheckerValue();
                        });
                        $(EntityRecordsModel.dialogid + ' button[name=searchBtn]').off('click').on('click',null,function(e){
                            EntityRecordsModel.enterSearch(e);
                        });
                        $(EntityRecordsModel.dialogid + ' button[name=createBtn]').off('click').on('click',null,function(e){
                            EntityRecordsModel.CreateRecord();
                        });
                        $(EntityRecordsModel.dialogid + ' button[name=deleteBtn]').off('click').on('click',null,function(e){
                            EntityRecordsModel.DeleteRecord();
                        });
                        $(EntityRecordsModel.dialogid + ' .dropdown-menu').on('click','>li>a',function(e){
                            $(EntityRecordsModel.dialogid + ' #QField').val($(this).attr('data-name'))
                            $(EntityRecordsModel.dialogid + ' #fieldDropdown').find('span:first').text($(this).text());
                        });
                        $('body').off('click.selectentitydialog').on('click.selectentitydialog',EntityRecordsModel.dialogid + ' .selectBtn',function(e){
                            Xms.Web.SelectingRow(this);
                            EntityRecordsModel.dialog_return(this);
                        });

                        $(EntityRecordsModel.dialogid + " button[name='returnBtn']").click( function() {
                            EntityRecordsModel.dialog_return();
                        });
                        $(EntityRecordsModel.dialogid + " #Q").off('keydown.enter').on('keydown.enter', function(e) {
                            e = e || window.event;
                            if(e.keyCode==13){
                                EntityRecordsModel.enterSearch(e);
                            }
                        });

                        $('#filterSearcher').tableFiler({
                            table:$('#entityRecordsModal .datatable')
                            ,styles:"customer-filter-style"
                            ,clear:function(pluger,filters){
                                EntityRecordsModel.cacheFilters = new Xms.Fetch.FilterExpression();
                                EntityRecordsModel.rebind(null);
                            }
                            ,confirm:function(pluger,filters){
                                //if(EntityRecordsModel.filters.conditions.length>1){
                                //     EntityRecordsModel.filters.conditions = EntityRecordsModel.filters.conditions.slice(0,1);
                                // }
                                var _filter = new Xms.Fetch.FilterExpression();
                                $.each(filters,function(key,filter){
                                    if (filter.Conditions[0]
                                        && typeof filter.Conditions[0].Values === "object" && filter.Conditions[0].Values.length
                                        && filter.Conditions[0].Values[0].replace("\s", "") != ""
                                        || (filter.Conditions[0] && filter.Conditions[0].Values && filter.Conditions[0].Values.length>0 && filter.Conditions[0].Values[1] && filter.Conditions[0].Values[1].replace("\s", "") != "")
                                    ) {
                                        _filter.Filters.push(this);
                                    }

                                });
                                EntityRecordsModel.cacheFilters = _filter;
                                EntityRecordsModel.rebind();
                            }
                        });
                        console.log($('.selectEntityRecords-datagrid'))
                    });

                    window["EntityRecordsModel"+MODAL_GUID] = EntityRecordsModel;
                })();
            </script>
            </div>
            <div class="modal-footer" style="padding:5px;">
                <div class="pull-left hide">
                    <button type="button" class="btn btn-link" name="createBtn">
                        <span class="glyphicon glyphicon-plus-sign"></span> 新增
                    </button>
                </div>
                <button type="button" class="btn btn-sm btn-default"
                        data-dismiss="modal">
                    <span class="glyphicon glyphicon-remove"></span> 关闭
                </button>
                <button type="button" class="btn btn-sm btn-primary" name="returnBtn">
                    <span class="glyphicon glyphicon-ok"></span> 确定
                </button>
            </div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal-dialog -->
</div><!-- /.modal -->